package org.zuel.huhuForum.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.zuel.huhuForum.component.SendMsg;
import org.zuel.huhuForum.constant.CommunityConstant;
import org.zuel.huhuForum.model.User;
import org.zuel.huhuForum.param.Event;
import org.zuel.huhuForum.service.ILikeService;
import org.zuel.huhuForum.util.HostHolder;
import org.zuel.huhuForum.util.RedisKeyUtil;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "点赞相关")
@RestController
@RequestMapping("/like")
public class LikeController implements CommunityConstant {

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private ILikeService likeService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SendMsg  eventProducer;

    /**
     * 点赞
     * @param entityType
     * @param entityId
     * @param entityUserId 赞的帖子/评论的作者 id
     * @param postId 帖子的 id (点赞了哪个帖子，点赞的评论属于哪个帖子，点赞的回复属于哪个帖子)
     * @return
     */
    @CrossOrigin
    @PostMapping("/like")
    @ApiOperation(value = "点赞/取消点赞（点赞后再次点赞即取消）")
    public Map<String, Object> like(@RequestParam(name="entityType", required = true)int entityType,
                                    @RequestParam(name="entityId", required = true)int entityId,
                                    @RequestParam(name="entityUserId", required = true)int entityUserId,
                                    @RequestParam(name="postId", required = true)int postId) {
        User user = hostHolder.getUser();
        // 点赞
        likeService.like(user.getId(), entityType, entityId, entityUserId);
        // 点赞数量
        long likeCount = likeService.findEntityLikeCount(entityType, entityId);
        // 点赞状态
        int likeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);
        Map<String, Object> map = new HashMap<>();
        map.put("likeCount", likeCount);
        map.put("likeStatus", likeStatus);
        if (likeStatus == 1) {
            Event event = new Event()
                    .setTopic(TOPIC_LIKE)
                    .setUserId(hostHolder.getUser().getId())
                    .setEntityType(entityType)
                    .setEntityId(entityId)
                    .setEntityUserId(entityUserId)
                    .setData("postId", postId);
            eventProducer.fireEvent(event);
        }
        if (entityType == ENTITY_TYPE_POST) {
            // 计算帖子分数
            String redisKey = RedisKeyUtil.getPostScoreKey();
            redisTemplate.opsForSet().add(redisKey, postId);
        }
        map.put("code", "200");
        return map;
    }

}

